package com.ph.demo.JDKcurrent;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by peng on 2019/4/10.
 */
public class TimeLock extends Thread{

    public static final ReentrantLock lock = new ReentrantLock(true);  //是否公平锁

    public static  int i = 0;

    @Override
    public void run() {
            try {
                //if(lock.tryLock(5, TimeUnit.SECONDS)){
                //    System.out.println("获得锁");
                //    i++;
                //    Thread.sleep(6000);
                //}else{
                //    System.out.println("没有获得锁");
                //}
                lock.lock();
                    System.out.println("开始放烟花");

                    Thread.sleep(5000);
                    System.out.println("烟花结束");

            } catch (Exception e) {
                e.printStackTrace();

            } finally {
                if(lock.isHeldByCurrentThread()) {  //查看当前线程是否保持此锁
                    lock.unlock();  //一定要释放锁
                }
                //lock.unlock();
            }


    }

    public static void main(String[] args) throws Exception{
        Thread[] ts = new Thread[3];

        for (int j = 0; j <3 ; j++) {
            ts[j] = new TimeLock();
            ts[j].start();
        }
        for (int j = 0; j <3 ; j++) {
            ts[j].join();
        }
        System.out.println(i);
    }
}
